
const { menu_controller_find } = require('../../controller/system/menu/MENU.CONTROLLER');
const { login } = require('../../controller/system/user/USER.CONTROLLER');
const { serverError } = require('../../utils');
const { emptyCheck } = require('../../utils/checkEmpty');
const { getMenuTree, getMenuTreeForPermission } = require('../../utils/getMenuTree')
const { getDocumentDetail: getRoleForUser } = require("../../controller/system/user/r_role_user");
const { findPermissions: getPermissionForRoleId } = require("../../controller/r_role_permission");


const router = require('koa-router')()

router.prefix('/auth')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

// 用户登录
router.post("/login", async (ctx, next) => {
  try {
    const { userId, passWord } = ctx.request.body;
    const check = emptyCheck({ userId, passWord })
    if (check.code !== 0) {
      ctx.body = check;
    } else {
      const res = await login({ userId, passWord, })
      ctx.body = res
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      code: "1000",
      msg: "服务器故障",
    }
  }

})
// 获取用户的菜单权限配置
router.get('/permission', async (ctx, next) => {
  try {
    const { userId, pageSize, current } = ctx.query
    // 根据userId查询归属的角色组；
    const roleForUser = await getRoleForUser({ userId })
    // console.log("查询到用户归属的组：", roleForUser)
    const { roleId, roleName, userName } = roleForUser;
    // 根据roleId 查询拥有的按钮权限;
    const permissionList = await getPermissionForRoleId({ role_id: roleId })
    // console.log("当前用户的permissionList有：\n", permissionList);

    // 查询所有菜单权限数据；
    const { list, totalCount } = await menu_controller_find({ pageSize, current });

    const tree = getMenuTree(list, "0", filterMenuTypeList = ["3"]);//获取全部菜单树,要过滤的菜单类型是按钮
    // console.log("当前用户的菜单树有：\n", tree);
    // 拿到树了，再遍历，把不在permission中的menu菜单去掉;
    const menus = getMenuTreeForPermission(tree, permissionList);//有权限的菜单树；

    ctx.body = {
      code: 0,
      msg: "查询成功",
      data: {
        totalCount: totalCount,
        menus: menus,
        permissionList: permissionList,
      }
    };
  } catch (error) {
    console.log(error);
    ctx.body = serverError
  }

})




module.exports = router
